<script setup>

	import {ref, reactive} from 'vue'
	import {useRouter} from "vue-router"
    import cartItemApi from '@/api/cart/cartItem'

	const router = useRouter()

    const data = reactive({
        cartItemList: [],
        checked: [],
        checkAll: true,
        totalAmount: 0,
        isEdit: false
    })

    const initData = () => {
        cartItemApi.getCartItemList().then(response => {
            data.cartItemList = response.data

            data.checked = data.cartItemList.map(e => e.id)

            data.checkAll = true

            getTotalAmount()
        })
    }
    const getTotalAmount = () => {
        cartItemApi.getTotalAmountByIds(data.checked).then(response => {
            data.totalAmount = response.data
        })
    }
    initData()

    const changeChecked = () => {
        const isAll = data.checked.length === data.cartItemList.length && data.checked.length > 0
        data.checkAll = isAll
        getTotalAmount()
    }

    const checkboxGroup = ref(null)
    const checkAll = () => {
        let hasChecked = data.checked.length > 0 && data.checked.length < data.cartItemList.length
        if(hasChecked){
            checkboxGroup.value.toggleAll(true)
        }else {
            checkboxGroup.value.toggleAll()
        }
        getTotalAmount()

    }

    //备份
    let checkBak = []
    const manageCart = () => {
        data.isEdit = !data.isEdit

        if(data.isEdit){
            checkBak = [...data.checked]
            data.checked = []
            data.totalAmount = 0
        }else {
            data.checked = [...checkBak]
            getTotalAmount()
        }


    }

    import { showConfirmDialog } from 'vant'
    const handleSubmit = () => {
        if (data.isEdit) {
            //删除
            showConfirmDialog({
                message: '确认删除所选商品吗？',
            }).then(() => {
                // on confirm
                cartItemApi.batchDeleteByIds(data.checked).then(response => {
                    initData()
                })
            }).catch(() => {
                // on cancel
            })
        }else{
            //提交订单
            router.push({
                name: 'OrderPreview',
                query: {
                   cartIds: data.checked
                }
            })
        }
    }

    const changeQuantity = (value, detail) => {
        if (value == '' || value == null) {
            return
        }
        cartItemApi.updateQuantityById({id: detail.name, quantity:value}).then(res => {
            getTotalAmount()
        }).catch(e => {
            initData()
        })
    }

</script>

<template>
	<van-nav-bar title="购物车" :right-text="data.isEdit ? '完成':'管理'" @click-right="manageCart"/>

	<div class="tab-cart">
		<van-checkbox-group class="card-goods" ref="checkboxGroup" v-model="data.checked" @change="changeChecked">
			<div class="card-goods__item" v-for="cartItem in data.cartItemList"><!---->

				<van-checkbox :key="cartItem.id" :name="cartItem.id"></van-checkbox>

				<van-card
						:title="cartItem.productName"
						:price="cartItem.price"
						:thumb="cartItem.productImage"
						@click-thumb="$router.push('/product/' + cartItem.productId)"
				>
					<template #tags>
						<van-tag color="#c8c9cc" text-color="white" style="margin: 6px 6px 0 0;" v-for="it in cartItem.sku.split(';')">{{it}}</van-tag>
					</template>
					<template #num>
						<van-stepper integer v-model="cartItem.quantity" :name="cartItem.id" @change="changeQuantity"/>
					</template>
				</van-card>
			</div>
		</van-checkbox-group>

		<van-empty v-if="data.cartItemList.length === 0" description="购物车空空如也，快去逛逛"/>
		<van-submit-bar
				style="margin-bottom: 51px;"
                v-if="data.cartItemList.length > 0"
				:price="data.totalAmount * 100"
				:buttonText="data.isEdit ? '删除所选':'提交订单'"
                :disabled="data.checked.length === 0"
				@submit="handleSubmit"
		>
			<van-checkbox style="padding: 0 10px;" v-model="data.checkAll" @click="checkAll">全选</van-checkbox>
		</van-submit-bar>
	</div>
</template>

<style lang="scss" scoped>

	.card-goods {
		margin: 8px;

		.card-goods__item {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
			background-color: #fff;
		}
	}

</style>
